package com.zhaoyue.study.concurrency.example.array;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * User: zhaoyue
 * Date: 2016/9/7
 * Time: 17:27
 * 无锁并发数据容器
 * AtomicInteger 原子操作
 *
 */
public class ConcurrentArrayQueue<T> {

    private final Object[] ring;
    private final AtomicInteger maxmumReadIndex = new AtomicInteger(0);
    private final AtomicInteger readIndex = new AtomicInteger(0);
    private final AtomicInteger writeIndex = new AtomicInteger(0);


    public ConcurrentArrayQueue(int capacity){
        if(capacity <0){
            throw new IllegalArgumentException("capacity:"+capacity);
        }
        ring = new Object[capacity];
    }

    public boolean push(T e){
        int currentReadIndex;
        int currentWriteIndex;

        do{
            currentReadIndex = readIndex.get();
            currentWriteIndex =writeIndex.get();

            if(((currentWriteIndex+1)%ring.length) == currentReadIndex%ring.length){
                return false;
            }

        }while (!writeIndex.compareAndSet(currentWriteIndex,currentWriteIndex+1));

        ring[currentWriteIndex % ring.length] = e;

        while (!maxmumReadIndex.compareAndSet(currentWriteIndex,currentWriteIndex+1)){
            Thread.yield();
        }
        return true;
    }

    public T pop(){

        //int currentMaxi

        return null;
    }









}
